<template>
  <div class="weather-forecast-container">
    <div class="weather-content">
      <!-- 实时天气 -->
      <div class="current-weather">
        <div class="weather-header">商丘学院智慧农业实训中心</div>
        <div class="weather-header1">实训中心始建于2012年，占地4000余平方米，是集 教学、科研、实训、社会服务于一体的综合性实践基地。2017年获批“河南省实验教学示范中心”，目前承担园艺园林专业10余门课程的实践教学任务，累计开展科研项目20多项。</div>
        <div class="weather-date" v-if="currentWeather.reporttime">
          {{ formatDate(currentWeather.reporttime) }}
        </div>
        <div class="weather-main">
          <div class="temperature">{{ currentWeather.temperature || '--' }}°C</div>
          <div class="weather-info">
            <div class="weather-condition">{{ currentWeather.weather || '未知' }}</div>
            <div class="feels-like">体感温度 {{ currentWeather.temperature || '--' }}°C</div>
          </div>
        </div>
        <div class="weather-details">
          <div class="detail-item">
            <span class="label">风向:</span>
            <span class="value">{{ currentWeather.winddirection ? currentWeather.winddirection + '风' : '--' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">风力:</span>
            <span class="value">{{ currentWeather.windpower ? currentWeather.windpower + '级' : '--' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">湿度:</span>
            <span class="value">{{ currentWeather.humidity ? currentWeather.humidity + '%' : '--' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">气压:</span>
            <span class="value">{{ currentWeather.pressure ? currentWeather.pressure + 'hPa' : '--' }}</span>
          </div>
        </div>
      </div>

      <!-- 天气预报 -->
      <div class="forecast-weather" v-if="forecastWeatherList.length > 0">

        <div class="forecast-list">
          <div class="forecast-item" v-for="(forecast, index) in forecastWeatherList" :key="index">
            <div class="forecast-date">{{ formatForecastDate(forecast.date) }} {{ getWeekDay(forecast.week) }}</div>
            <div class="forecast-condition">
              <div class="day-weather">
                <span class="time-label">白天:</span>
                <span>{{ forecast.dayweather }}</span>
                <span class="wind-info">{{ forecast.daywind }}风{{ forecast.daypower }}级</span>
              </div>
              <div class="night-weather">
                <span class="time-label">夜间:</span>
                <span>{{ forecast.nightweather }}</span>
                <span class="wind-info">{{ forecast.nightwind }}风{{ forecast.nightpower }}级</span>
              </div>
            </div>
            <div class="forecast-temp">{{ forecast.nighttemp }}°C ~ {{ forecast.daytemp }}°C</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

// 定义响应式数据
const currentWeather = ref({
  city: '',
  weather: '',
  temperature: '',
  winddirection: '',
  windpower: '',
  humidity: '',
  pressure: '',
  visibility: '',
  reporttime: ''
})

const forecastWeatherList = ref<any[]>([])

// 格式化预报日期
const formatForecastDate = (dateString: string) => {
  if (!dateString) return '--'
  const date = new Date(dateString)
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${month}月${day}日`
}

// 格式化当前天气日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${year}年${month}月${day}日`
}

// 获取星期
const getWeekDay = (week: string) => {
  const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  const weekIndex = parseInt(week, 10)
  return weekDays[weekIndex] || ''
}

// 获取天气数据
const fetchWeatherData = async () => {
  try {
    // 使用高德天气API获取商丘梁园区天气数据
    const key = '5957209a767a041fae36b1e7eb2eb404'
    // 商丘梁园区adcode为411402
    // 获取预报数据
    const url = `https://restapi.amap.com/v3/weather/weatherInfo?city=411402&key=${key}&extensions=all`

    const response = await fetch(url)

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data = await response.json()

    // 检查预报数据
    if (data.status === '1' && data.forecasts && data.forecasts.length > 0) {
      // 设置预报天气数据（当天和第二天）
      if (data.forecasts[0].casts && data.forecasts[0].casts.length > 0) {
        // 显示当天和未来几天的预报
        forecastWeatherList.value = data.forecasts[0].casts.slice(1, 2)
      }

      // 获取实时天气数据需要另一个API调用
      try {
        const realtimeUrl = `https://restapi.amap.com/v3/weather/weatherInfo?city=411402&key=${key}&extensions=base`
        const realtimeResponse = await fetch(realtimeUrl)
        if (realtimeResponse.ok) {
          const realtimeData = await realtimeResponse.json()
          if (realtimeData.status === '1' && realtimeData.lives && realtimeData.lives.length > 0) {
            currentWeather.value = {
              city: realtimeData.lives[0].city,
              weather: realtimeData.lives[0].weather,
              temperature: realtimeData.lives[0].temperature,
              winddirection: realtimeData.lives[0].winddirection,
              windpower: realtimeData.lives[0].windpower,
              humidity: realtimeData.lives[0].humidity,
              pressure: realtimeData.lives[0].pressure,
              visibility: realtimeData.lives[0].visibility,
              reporttime: realtimeData.lives[0].reporttime
            }
          }
        }
      } catch (realtimeError) {
        console.error('获取实时天气数据失败:', realtimeError)
      }
    } else {
      throw new Error('API返回数据格式不正确')
    }
  } catch (error) {
    console.error('获取天气数据失败:', error)
  }
}

onMounted(() => {
  fetchWeatherData()
})
</script>

<style scoped>
.weather-forecast-container {
  width: 100%;
  height: 100%;
  color: #ffffff;
  font-size: 14px;
  padding: 20px;
  box-sizing: border-box;
  background: transparent;
}

.weather-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  margin-top: -10%;
}

.weather-header {
  text-align: center;
  font-size: 16px;
  color: #0efcff;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #0efcff;
}
.weather-header1 {
  text-align: left;
  font-size: 16px;
  color: #0efcff;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #0efcff;
}

.current-weather {
  flex: 1;
}

.weather-main {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.weather-date {
  text-align: center;
  color: #0efcff;
  font-size: 14px;
  margin-bottom: 10px;
}

.temperature {
  font-size: 36px;
  font-weight: bold;
  color: #0efcff;
}

.weather-info {
  text-align: right;
}

.weather-condition {
  font-size: 16px;
  margin-bottom: 5px;
}

.feels-like {
  font-size: 14px;
  color: #0efcff;
}

.weather-details {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
}

.label {
  color: #ffffff;
}

.value {
  color: #0efcff;
  margin-left: 10px;
}

.forecast-weather {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid rgba(14, 252, 255, 0.3);
}

.forecast-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.forecast-item {
  display: flex;
  flex-direction: column;
  padding: 10px 0;
  border-bottom: 1px solid rgba(14, 252, 255, 0.1);
}

.forecast-date {
  color: #0efcff;
  font-weight: bold;
  margin-bottom: 8px;
}

.forecast-condition {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.time-label {
  color: #0efcff;
  margin-right: 5px;
}

.day-weather, .night-weather {
  display: flex;
  align-items: center;
  gap: 10px;
}

.wind-info {
  color: #0efcff;
  font-size: 12px;
}

.forecast-temp {
  color: #0efcff;
  font-weight: bold;
  text-align: right;
  margin-top: 5px;
}
</style>
